package com.apexedu.portal.controller;

import com.apexedu.framework.util.ConfigUtil;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.portal.constant.ActionConstant;
import com.apexedu.portal.entity.TLbxx;
import com.apexedu.portal.entity.Workflow;
import com.apexedu.portal.entity.WorkflowResult;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.portal.util.LittleTimer;
import com.apexedu.util.crypto.DES;
import com.apexedu.util.json.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 桌面提醒获取待办
 * Created by ly on 2015/3/12.
 */
@Controller
public class TodoController extends BaseController {

    @RequestMapping("/pc_client/todo/{userid}")
    @ResponseBody
    public String todo(@PathVariable(ActionConstant.Variable_User_Id) String userid){
        String userloginid = null;
        try {
            userloginid = DES.decrypt(userid, ConfigUtil.getString("userid.key"));
        } catch (Exception e) {
            error("<<{}>> todo decrypt error : {}", this.getClass().getSimpleName(), e);
//            return "url parameter must be encrypt.";
            error("<<{}>> todo decrypt error : {}", this.getClass().getSimpleName(), "参数不是约定算法的密文，已作为明文处理");
            userloginid = userid; // 明文传输
        }
        debug("<<{}>> todo start : userloginid : {}", this.getClass().getSimpleName(), userloginid);
        LittleTimer timer = new LittleTimer();
        try {
            List<Workflow> list = new ArrayList<Workflow>();
            String sql = "select * from t_lbxx t where t.upid = '1'";
            List<TLbxx> lbxxList = DBUtil.queryAllBeanList(sql, TLbxx.class);

            sql = "select cur.entry_id as id,wf.subject as title,init_t.name as createname,to_char(wf.init_date,'yyyy-MM-dd') as time "
                    + "from os_wfentry wf left join os_currentstep cur on wf.id=cur.entry_id left join tuser t on instr(','||cur.owner||',',','||t.id||',')>0 left join "
                    + "tuser init_t on wf.initiator=init_t.id where t.userid= ? order by cur.start_date desc";
            for (TLbxx t : lbxxList) {
                list.addAll(new DBMUtil(t.getDb()).queryAllBeanList(sql, Workflow.class, userloginid));
            }
            WorkflowResult c = new WorkflowResult(list.size(), lbxxList);
            return JsonUtil.getJSONString(c);
        } catch (Exception e) {
            error("<<{}>> todo error : {}", this.getClass().getSimpleName(), e);
            throw new RuntimeException(e);
        } finally {
            debug("<<{}>> todo end : {}", this.getClass().getSimpleName(), timer.end());
        }
    }
}
